﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MH.CRM.Summary.CrmSdk;
using System.Windows.Media.Imaging;
using System.Windows.Browser;
using System.Text.RegularExpressions;

namespace MH.CRM.Summary
{
    public partial class ActivityRow : UserControl
    {
        public ActivityRow()
        {
            InitializeComponent();
        }

        public string LogicalName
        {
            get
            {
                return activityMetadata.LogicalName;
            }
        }

        
        public string Subject
        {
            get
            {
                return activity.GetAttributeValue<string>("subject");
            }
        }

        public Guid Id
        {
            get
            {
                return activity.GetAttributeValue<Guid>("activityid");
            }
        }

        public string Date
        {
            get
            {
                //if (activity.Attributes.ContainsKey("actualend"))
                //{
                //    return activity.GetAttributeValue<DateTime>("actualend").ToShortDateString(); 
                //}
                //else if (activity.Attributes.ContainsKey("scheduledend"))
                //{
                //    return activity.GetAttributeValue<DateTime>("scheduledend").ToShortDateString();
                //}
                //else
                //{
                    return activity.GetAttributeValue<DateTime>("createdon").ToShortDateString();
               // }
            }
        }

        public string From
        {
            get
            {
                try                
                {
                    Entity activityPartyFrom = activity_actitityParty.GetAttributeValue<EntityCollection>("from").Entities.First();
                    if (activityPartyFrom.Attributes.ContainsKey("partyid"))
                    {
                        return activityPartyFrom.GetAttributeValue<EntityReference>("partyid").Name;
                    }
                    else
                    {
                        return activityPartyFrom.GetAttributeValue<string>("addressused");
                    }
                }
                catch
                {
                    return activity.GetAttributeValue<EntityReference>("ownerid").Name;
                }
                
            }
        }

        public string To
        {
            get
            {
                string to = String.Empty;
                try
                {
                    foreach (Entity activityPartyFrom in activity_actitityParty.GetAttributeValue<EntityCollection>("to").Entities)
                    {
                        to = GetActivityPartyString(to, activityPartyFrom);
                    }
                }
                catch { }

                try
                {
                    foreach (Entity activityPartyFrom in activity_actitityParty.GetAttributeValue<EntityCollection>("requiredattendees").Entities)
                    {
                        to = GetActivityPartyString(to, activityPartyFrom);
                    }
                    foreach (Entity activityPartyFrom in activity_actitityParty.GetAttributeValue<EntityCollection>("optionalattendees").Entities)
                    {
                        to = GetActivityPartyString(to, activityPartyFrom);
                    }
                }
                catch { }

                if (activity.Attributes.ContainsKey("regardingobjectid"))
                {
                    if (to.IndexOf(activity.GetAttributeValue<EntityReference>("regardingobjectid").Name + ", ") == -1)
                    {
                        to += activity.GetAttributeValue<EntityReference>("regardingobjectid").Name;
                        to += ", ";
                    }
                }

                if (to != String.Empty)
                {
                    to = to.Substring(0, to.Length - 2);
                }
                
                return to;    
            
            }
        }

        private static string GetActivityPartyString(string to, Entity activityPartyFrom)
        {
            if (activityPartyFrom.Attributes.ContainsKey("partyid"))
            {
                if (to.IndexOf(activityPartyFrom.GetAttributeValue<EntityReference>("partyid").Name + ", ") == -1)
                {
                    to += activityPartyFrom.GetAttributeValue<EntityReference>("partyid").Name;
                    to += ", ";
                }
            }
            else
            {
                to += activityPartyFrom.GetAttributeValue<string>("addressused");
                to += ", ";
            }
            return to;
        }

        public string Description
        {
            get
            {
                if (activityMetadata.LogicalName.ToLower() == "email" && activity.GetAttributeValue<string>("description") != null)
                {
                    //return activity.GetAttributeValue<string>("description");
                    return StripHTML(activity.GetAttributeValue<string>("description").Replace("<br", "\r\n<br").Replace("</p", "\r\n</p"));
                }
                else
                {
                    return activity.GetAttributeValue<string>("description");
                }
            }
        }

        private string StripHTML(string str)
        {
            string strRegexScript = @"(?m)<body[^>]*>(\w|\W)*?</body[^>]*>";
            string strRegex = @"<[^>]*>";
            string strMatchScript = string.Empty;
            Match matchText = Regex.Match(str, strRegexScript, RegexOptions.IgnoreCase);
            strMatchScript = matchText.Groups[0].Value;
            string strPureText = string.Empty;
            if (strMatchScript != String.Empty)
            {
                strPureText = Regex.Replace(strMatchScript, strRegex, string.Empty, RegexOptions.IgnoreCase);
            }
            else
            {
                strPureText = Regex.Replace(str, strRegex, string.Empty, RegexOptions.IgnoreCase);
            }

            strPureText = strPureText.Replace("\r\n\r\n\r\n\r\n", "\r\n\r\n").Replace("\r\n\r\n\r\n", "\r\n\r\n");
            strPureText = System.Windows.Browser.HttpUtility.HtmlDecode(strPureText);
            return strPureText.Trim();
            //return strPureText.Replace("&nbsp;", " ").Replace("&gt;", ">").Replace("&lt;", ">").Replace("&quot;", "\"").Replace("&amp;", "&").Replace("&#8211;", "-").Replace("&#8222;","\"").Trim();
        }

        Entity activity;
        EntityMetadata activityMetadata;
        public void Init(Entity activity, EntityMetadata activityMetadata)
        {
            this.activity = activity;
            this.activityMetadata = activityMetadata;

            //Show entity icons
            if (activityMetadata.IsCustomEntity == false)
            {
                this.ImageIcon.Source = new BitmapImage(new Uri("/MH.CRM.Summary;component/imgs/ico_16_" + activityMetadata.ObjectTypeCode + ".png", UriKind.Relative));
            }
            else if (activityMetadata.IconSmallName == null)
            {
                this.ImageIcon.Source = new BitmapImage(new Uri("/MH.CRM.Summary;component/imgs/ico_16_CustomActivity.png", UriKind.Relative));                
            }
            else
            {
                this.ImageIcon.Source = new BitmapImage(new Uri(SilverlightUtility.GetServerBaseUrl() + "/WebResources/" + activityMetadata.IconSmallName, UriKind.Absolute));
            }
            
            //Show fields
            this.TextBlockSubject.Text = Subject;
            this.TextBlockOwner.Text = activity.GetAttributeValue<EntityReference>("ownerid").Name;
            this.TextBlockDate.Text = Date;            

            //Show status icons
            switch (activity.GetAttributeValue<OptionSetValue>("statecode").Value)
            {
                case 0: //open acitivity

                    break;
                case 1: //closed acitivity
                    this.ImageStatus.Source = new BitmapImage(new Uri("/MH.CRM.Summary;component/imgs/icon_done.png", UriKind.Relative));
                    break;
                case 2: //canceled acitivity
                    this.ImageStatus.Source = new BitmapImage(new Uri("/MH.CRM.Summary;component/imgs/icon_canceled.png", UriKind.Relative)); 
                    break;
            }

            //Get activites parties
            if (activityMetadata.LogicalName.ToLower() == "email"
                || activityMetadata.LogicalName.ToLower() == "phonecall"
                || activityMetadata.LogicalName.ToLower() == "letter"
                || activityMetadata.LogicalName.ToLower() == "fax"
                || activityMetadata.LogicalName.ToLower() == "appointment"
                || activityMetadata.IsCustomEntity == true
                )
            {
                IOrganizationService service = SilverlightUtility.GetSoapService();
                OrganizationRequest retriveReqest = new OrganizationRequest() { RequestName = "Retrieve" };
                retriveReqest["ColumnSet"] = new ColumnSet()
                {
                    Columns = activityMetadata.LogicalName.ToLower() == "appointment" ? new System.Collections.ObjectModel.ObservableCollection<string>() { "requiredattendees", "optionalattendees" } : new System.Collections.ObjectModel.ObservableCollection<string>() { "to", "from" }
                };
                if (activityMetadata.LogicalName.ToLower() == "email")
                {
                    ((ColumnSet)retriveReqest["ColumnSet"]).Columns.Add("cc");
                }

                retriveReqest["Target"] = new EntityReference()
                {
                    LogicalName = activityMetadata.LogicalName,
                    Id = activity.GetAttributeValue<Guid>("activityid")
                };
                service.BeginExecute(retriveReqest, new AsyncCallback(Retrive_Callback), service);
            }  
          

        }

        Entity activity_actitityParty = null;
        private void Retrive_Callback(IAsyncResult result)
        {
            OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);
            activity_actitityParty = (Entity)response["Entity"];
            this.TextBlockOwner.Dispatcher.BeginInvoke(() =>
                {
                    this.TextBlockOwner.Text = this.From + ", " + this.To;
                });
        }

        private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount > 1)
            {
                var options = new HtmlPopupWindowOptions { Location = false, Menubar = false, Toolbar = false };

                if (HtmlPage.IsPopupWindowAllowed)
                {
                    //HtmlPage.PopupWindow(new Uri("http://google.pl"), "_blank", options);
                    HtmlPage.Window.Navigate(new Uri(SilverlightUtility.GetServerBaseUrl() + "/main.aspx?etn=" + activityMetadata.LogicalName +"&pagetype=entityrecord&id=" + activity.GetAttributeValue<Guid>("activityid"))
                        , "_blank", "directories=no,fullscreen=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=yes,toolbar=no");
                    
                }
            }
        }


    }
}
